const argon2 = require('argon2')

const { adminUsers, Avatar } = require('../../schemas')
const { createToken } = require('../../utils/jwt.js')
const Snowflake = require('../../utils/snowflake.js')

const { phoneRegex, encryptPhone } = require('../../utils/index.js')

const snowflake = new Snowflake(1, 1)

// admin 登录
const Login = async (request, reply) => {
  const { phoneNo, password } = request.body || {}
  if (!phoneRegex(phoneNo)) {
    return reply.fail({ code: 400, msg: '手机号格式错误' })
  }

  try {
    const userData = await adminUsers.findOne({ phoneNo })

    const isPasswordValid =
      userData && (await argon2.verify(userData?.password, password))

    if (!userData || !isPasswordValid) {
      return reply.fail({ code: 404, msg: '用户名/密码错误' })
    }
    if (userData) {
      const token = await createToken({
        userName: userData.userName,
        roleNo: userData.roleNo,
      })
      return reply.success({
        msg: '登陆成功！',
        data: token,
      })
    } else {
      return reply.fail({
        msg: '未查到该用户信息！',
      })
    }
  } catch (error) {
    reply.fail({ code: 500, msg: '服务器内部错误' })
  }
}

// admin 用户详情
const AdminDetails = async (request, reply) => {
  const { userName } = request.query || {}
  if (userName) {
    const userData = await adminUsers.findOne(
      { userName },
      { _id: 0, __v: 0, phone: 0, password: 0 }
    )

    return reply.code(200).send({
      code: reply.statusCode,
      message: null,
      data: userData ? userData._doc : null,
      error: null,
    })
  } else {
    return reply.code(404).send({
      code: reply.statusCode,
      message: 'userNo 未定义',
      data: null,
      error: 'userNo 不能为空',
    })
  }
}

// admin 用户 删除
const Delete = async (request, reply) => {
  const { roleNo, userId } = request.query

  if (!userId) {
    return reply.fail({ code: 400, msg: '用户编号必填！' })
  }
  try {
    if (roleNo !== 10000) {
      return reply.fail({ code: 403, msg: '权限不足！' })
    }
    // 执行删除
    const result = await adminUsers.deleteOne({ userNo: userId })

    // 结果处理
    if (result.deletedCount > 0) {
      return reply.success({ msg: '删除成功！', data: null })
    } else {
      return reply.fail({ code: 404, msg: '删除失败！' })
    }
  } catch (error) {
    reply.fail({ code: 500, msg: '服务器内部错误！' })
  }
}

// admin 用户 添加
const Register = async (request, reply) => {
  const { phoneNo, password } = request.body
  try {
    const existingUser = await adminUsers.findOne({ phoneNo })
    if (existingUser) {
      return reply.fail({ code: 400, msg: '手机号已存在！' })
    }
    const hashedPassword = await argon2.hash(password)

    const userNo = snowflake.generateUserId()

    const userModel = new adminUsers({
      ...request.body,
      password: hashedPassword,
      hashPhone: encryptPhone(phoneNo),
      userNo,
    })
    await userModel.save()
    return reply.success({ msg: '注册成功！' })
  } catch (error) {
    return reply.fail({
      code: 500,
      msg: '服务器内部错误',
      errorMsg: error.message,
    })
  }
}
// 用户列表
const List = async (request, reply) => {
  const { currentPage = 1, pageSize = 10 } = request.query

  try {
    let page = parseInt(currentPage, 10)
    let size = parseInt(pageSize, 10)

    if (page < 1) page = 1
    if (size < 1) size = 10

    const skip = (page - 1) * size
    const total = await adminUsers.countDocuments().exec()

    const dataList = await adminUsers
      .find({}, { _id: 0, __v: 0, password: 0, phoneNo: 0 })
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(size)
      .exec()

    if (dataList) {
      return reply.success({
        message: '成功！',
        data: dataList,
        currentPage: page,
        currentSize: size,
        total,
        totalPages: Math.ceil(total / pageSize),
      })
    }
  } catch (error) {
    reply.fail({ code: 500, msg: '服务器内部错误' })
  }
}

module.exports = {
  Login,
  List,
  AdminDetails,
  Delete,
  Register,
}
